<?php


namespace App\Services\Game;


use App\DTOS\Admin\UserRoleDTO;
use App\DTOS\Admin\PackageDTO;
use App\Models\Game\PackageRecord;
use App\Models\Game\RoleIds;
use App\Models\Game\Server;
use Illuminate\Support\Facades\Http;
use App\Utils\MyLog;
use Illuminate\Support\Facades\Log;

class PackageService
{
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    /**
     * PackageService constructor.
     * @param UserRoleService $userRoleService
     * @param UserMemberService $userMemberService
     */
    public function __construct(UserRoleService $userRoleService, UserMemberService $userMemberService)
    {
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }

    public function sendEmailById($recordId){ //通过邮件ID发送邮件

        $packageRecord = PackageRecord::query()->find($recordId);
        $sendAreas = $packageRecord->game_areas; //array
        $QueryType = null;
        $RoleIdList = []; //目标角色的角色ID列表
        $AttaItems = []; //附件物品列表
        $AttaMoney = [];  //附件游戏币列表
        $roleIds = [];
        $createDateTimeBegin=0;
        $createDateTimeEnd=0;
        $MailType_RMB_Max=0;
        $MailType_RMB_Min=0;
        $minLevel=0;
        $maxLevel=100;
        switch($packageRecord->object){
            case 0: //全区
                $QueryType = 3;
            break;
            case 1: //指定的角色ID
                $QueryType = 1;
                $roles = $packageRecord->roles;
                $roleIds = collect($roles)->pluck('id')->toArray();
                break;
            case 2: //限定等级
                $QueryType = 2;
                $level_range = $packageRecord->level_range;
                $ranges = explode(',',$level_range);
                $minLevel = (int)$ranges[0];
                $maxLevel = (int)$ranges[1];
                $createDateTimeBegin = strtotime($packageRecord->createDateTimeBegin);
                $createDateTimeEnd = strtotime($packageRecord->createDateTimeEnd);
                $MailType_RMB_Max = $packageRecord->MailType_RMB_Max;
                $MailType_RMB_Min= $packageRecord->MailType_RMB_Min;
                break;
            case 3: //从导入角色ID中获取
                $QueryType = 0;
                $roleIds = RoleIds::query()->get()->toArray();
                break;
        }
        foreach($roleIds as $id){
            $RoleIdList[] = [
                'roleid'=>$id
            ];
        }
        if ($packageRecord->item){
            $items = $packageRecord->item;
            foreach ($items as $item){
                $AttaItems[] = [
                    'id'=>(int)$item['itemId'],
                    'count'=>(int)$item['number'],
                    "IsBinding"=> (int)$item['isBind']

                ];
            }
        }
        if ($packageRecord->coin){
            $coins = $packageRecord->coin;
            foreach ($coins as $item){
                $AttaMoney[] = [
                    'id'=>(int)$item['coinType'],
                    'count'=>(int)$item['number'],
                ];
            }
        }
        $requestBody = [
            'MailType'=> $QueryType ,//0.按收件人列表发送 1.本区所有角色
            'MailType_Level_Min'=>$minLevel,
            'MailType_Level_Max'=>$maxLevel,
            'MailType_RoleTime_Min'=>$createDateTimeBegin,
            'MailType_RoleTime_Max'=>$createDateTimeEnd,
            'MailType_RMB_Max'=>$MailType_RMB_Max,
            'MailType_RMB_Min'=>$MailType_RMB_Min,
            'MailTitle'=>$packageRecord->title,
            'MailContent'=>$packageRecord->content,
            'SenderName'=>'系统',
            'RoleIdList'=>empty($RoleIdList) ? []  : $RoleIdList,
            'AttachItems'=>empty($AttaItems) ? [] : $AttaItems,
            'AttachMoney'=>empty($AttaMoney) ? []  : $AttaMoney,
        ];

        foreach($sendAreas as $areaCode){
            $row = Server::query()->where('can_push',1)->where("server_id",$areaCode)->first();
            $pushUrl = data_get($row,'push_url');
            MyLog::info('请求参数'.json_encode($requestBody));
            $response = Http::withHeaders(['Content-Type'=>'application/json'])
                ->timeout(5)
                ->post($pushUrl.'/Api/Mail/Add',$requestBody);

            if (PHP_SAPI === 'cli'){
                MyLog::info("邮件发送： " . json_encode($requestBody));
            } else {
                MyLog::info("邮件发送： " . json_encode($requestBody));
            }

            $body = json_decode($response->body(),true);
            $RetCode = data_get($body,'RetCode');
            MyLog::info('返回参数'.json_encode($RetCode));

            if ($RetCode == 1000) {
                throw new \Exception('参数错误');
            } else if($RetCode==2000){
                //throw new \Exception('操作正在处理');
                $packageRecord->send_status = 1;
                $packageRecord->save();
                return true;
            } else if ($RetCode == 0 ) {
                $packageRecord->send_status = 1;
                $packageRecord->save();
                return true;
            } else {
                throw new \Exception('错误代码:' . $RetCode);
            }
        }
    }





    public function paginate(PackageDTO $packageDTO){
        $perPage = $packageDTO->getLimit();
        $page = $packageDTO->getPage();
        $type = $packageDTO->getType();
        $model = PackageRecord::query();
        if ($type!==null) {
            $model->where('type',$type);
        }
        return $model->orderByDesc('id')->paginate($perPage,'*','page',$page);
    }


}

